using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using Resources;
using ud_Forum.Business;

namespace ud_Forum
{
    public partial class ForumView : mojoBasePage
	{
        protected int PageId = -1;
        protected int ModuleId = -1;
        protected int ItemId = -1;
		private int pageNumber = 1;
        protected bool EnableRssAtThreadLevel;
        private Hashtable moduleSettings;
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected string notificationUrl = string.Empty;
        protected bool isSubscribedToForum;
        private bool showForumSearchBox = true;
        private SiteUser currentUser;
        private bool userCanEdit;
        

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            Load += Page_Load;
            base.OnInit(e);
        }

        #endregion


        private void Page_Load(object sender, EventArgs e)
		{
            if (Page.IsPostBack) return;

            if ((siteSettings != null)&&(CurrentPage != null))
            {
                if ((SiteUtils.SslIsAvailable())
                    &&((siteSettings.UseSslOnAllPages)||(CurrentPage.RequireSsl))
                    )
                {
                    SiteUtils.ForceSsl();
                }
                else
                {
                    SiteUtils.ClearSsl();
                }

            }

            LoadParams();

            if (!UserCanViewPage(ModuleId, Forum.FeatureGuid))
            {
                if (!Request.IsAuthenticated)
                {
                    SiteUtils.RedirectToLoginPage(this);
                    return;
                }
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            SetupCss();
            PopulateLabels();
            
            GetModuleSettings();
#if MONO
            rptForums.DataBind();
#else
            DataBind();
#endif
			PopulateControls();

            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsForumSection", "forums");

		}

		

		private void PopulateControls()
		{
			Forum forum = new Forum(ItemId);
            if (forum.ModuleId != ModuleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            Title = SiteUtils.FormatPageTitle(siteSettings, forum.Title);

            litForumTitle.Text = forum.Title;
			litForumDescription.Text = forum.Description;
            divDescription.Visible = (forum.Description.Length > 0);

            MetaDescription = string.Format(CultureInfo.InvariantCulture, ForumResources.ForumMetaDescriptionFormat, forum.Title);

            string pageUrl = siteSettings.SiteRoot 
				+ "/Forums/ForumView.aspx?"
				+ "ItemID=" + forum.ItemId.ToInvariantString()
                + "&amp;mid=" + ModuleId.ToInvariantString()
                + "&amp;pageid=" + PageId.ToInvariantString()
				+ "&amp;pagenumber={0}";

            pgrTop.PageURLFormat = pageUrl;
            pgrTop.ShowFirstLast = true;
            pgrTop.CurrentIndex = pageNumber;
            pgrTop.PageSize = forum.ThreadsPerPage;
            pgrTop.PageCount = forum.TotalPages;
            pgrTop.Visible = (pgrTop.PageCount > 1);

            pgrBottom.PageURLFormat = pageUrl;
            pgrBottom.ShowFirstLast = true;
            pgrBottom.CurrentIndex = pageNumber;
            pgrBottom.PageSize = forum.ThreadsPerPage;
            pgrBottom.PageCount = forum.TotalPages;
            pgrBottom.Visible = (pgrBottom.PageCount > 1);

			if((Request.IsAuthenticated)||(forum.AllowAnonymousPosts))
			{
                //lnkNewThread.InnerHtml = "<img alt='' src='" + siteSettings.SiteRoot + "/Data/SiteImages/" + NewThreadImage + "'  />&nbsp;"
                //    + ForumResources.ForumViewNewThreadLabel;

                lnkNewThread.InnerHtml = ForumResources.ForumViewNewThreadLabel;
                lnkNewThread.Title = ForumResources.ForumViewNewThreadLabel;

                lnkNewThread.HRef = siteSettings.SiteRoot
                    + "/Forums/EditPost.aspx?forumid=" + ItemId.ToInvariantString()
                    + "&amp;pageid=" + PageId.ToInvariantString()
                    + "&amp;mid=" + ModuleId.ToInvariantString();

                //lnkNewThreadBottom.InnerHtml = "<img alt='' src='" + siteSettings.SiteRoot + "/Data/SiteImages/" + NewThreadImage + "'  />&nbsp;"
                //    + ForumResources.ForumViewNewThreadLabel;
                lnkNewThreadBottom.InnerHtml = ForumResources.ForumViewNewThreadLabel;
                lnkNewThreadBottom.Title = ForumResources.ForumViewNewThreadLabel;

                lnkNewThreadBottom.HRef = siteSettings.SiteRoot
                    + "/Forums/EditPost.aspx?forumid=" + ItemId.ToInvariantString()
                    + "&amp;pageid=" + PageId.ToInvariantString()
                    + "&amp;mid=" + ModuleId.ToInvariantString();
                
                lnkLogin.Visible = false;

			}

            lnkLogin.NavigateUrl = SiteRoot + "/Secure/Login.aspx";
            lnkLogin.Text = ForumResources.ForumsLoginRequiredLink;

            if (Page.Header != null)
            {

                Literal link = new Literal {ID = "forumurl"};

                string canonicalUrl = siteSettings.SiteRoot
                    + "/Forums/ForumView.aspx?"
                    + "ItemID=" + forum.ItemId.ToInvariantString()
                    + "&amp;mid=" + ModuleId.ToInvariantString()
                    + "&amp;pageid=" + PageId.ToInvariantString()
                    + "&amp;pagenumber=" + pageNumber.ToInvariantString();

                link.Text = @"<link rel='canonical' href='" + canonicalUrl + @"' />";

                Page.Header.Controls.Add(link);
            }

            using (IDataReader reader = forum.GetThreads(pageNumber))
            {
                rptForums.DataSource = reader;
                rptForums.DataBind();
            }

		}


		public bool GetPermission(object startedByUser)
		{
            // TODO: allow the user who started the thread to edit it?
			
			return userCanEdit;
		}


        private void GetModuleSettings()
        {
            if (ModuleId == -1) { return; }

            moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            EnableRssAtThreadLevel = WebUtils.ParseBoolFromHashtable(moduleSettings, "ForumEnableRSSAtThreadLevel", EnableRssAtThreadLevel);
            showForumSearchBox = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "ShowForumSearchBox", showForumSearchBox);

            if (!showForumSearchBox) { searchBox1.Visible = false; }

        }

        protected string GetRowCssClass(int stickySort, bool isLocked)
        {
            if (isLocked) { return "lockedthreadrow"; }
            if (stickySort < Forum.NormalThreadSort) { return "stickythreadrow"; }

            return "normalthreadrow";

        }

        protected string GetFolderCssClass(int stickySort, bool isLocked)
        {
            if (isLocked) { return "lockedthread"; }
            if (stickySort < Forum.NormalThreadSort) { return "stickythread"; }

            return "normalthread";

        }

        protected string FormatDate(DateTime startDate)
        {
            if (timeZone != null)
            {
                return TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString();

            }

            return startDate.AddHours(TimeOffset).ToString();

        }
        

        private void PopulateLabels()
        {
            lnkPageCrumb.Text = CurrentPage.PageName;
            lnkPageCrumb.NavigateUrl = SiteUtils.GetCurrentPageUrl();
            //EditAltText = Resource.EditImageAltText;
            pgrTop.NavigateToPageText = ForumResources.CutePagerNavigateToPageText;
            pgrTop.BackToFirstClause = ForumResources.CutePagerBackToFirstClause;
            pgrTop.GoToLastClause = ForumResources.CutePagerGoToLastClause;
            pgrTop.BackToPageClause = ForumResources.CutePagerBackToPageClause;
            pgrTop.NextToPageClause = ForumResources.CutePagerNextToPageClause;
            pgrTop.PageClause = ForumResources.CutePagerPageClause;
            pgrTop.OfClause = ForumResources.CutePagerOfClause;

            pgrBottom.NavigateToPageText = ForumResources.CutePagerNavigateToPageText;
            pgrBottom.BackToFirstClause = ForumResources.CutePagerBackToFirstClause;
            pgrBottom.GoToLastClause = ForumResources.CutePagerGoToLastClause;
            pgrBottom.BackToPageClause = ForumResources.CutePagerBackToPageClause;
            pgrBottom.NextToPageClause = ForumResources.CutePagerNextToPageClause;
            pgrBottom.PageClause = ForumResources.CutePagerPageClause;
            pgrBottom.OfClause = ForumResources.CutePagerOfClause;

            

        }

        private void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("forumcss") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "forumcss",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             +
                                             @"forummodule.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }

        private void LoadParams()
        {
            PageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            ModuleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            ItemId = WebUtils.ParseInt32FromQueryString("ItemID", -1);
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1);
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();

            userCanEdit = UserCanEditModule(ModuleId);

            //if (Settings.Contains("CustomCssClassSetting"))
            //{
            //    instanceCssClass = Settings["CustomCssClassSetting"].ToString();
            //}
            //if (instanceCssClass.Length > 0) { pnlForum.CssClass += " " + instanceCssClass; }

            notificationUrl = SiteRoot + "/Forums/EditSubscriptions.aspx?mid="
                + ModuleId.ToInvariantString()
                + "&pageid=" + PageId.ToInvariantString() +"#forum" + ItemId.ToInvariantString();

            if (Request.IsAuthenticated)
            {
                currentUser = SiteUtils.GetCurrentSiteUser();
                if ((currentUser != null)&&(ItemId > -1))
                {
                    isSubscribedToForum = Forum.IsSubscribed(ItemId, currentUser.UserId);
                }

                if (!isSubscribedToForum) { pnlNotify.Visible = true; }
                
            }

            AddClassToBody("forumview");

        }

       
	}
}
